<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <link rel="stylesheet" href="./css/bootstrap.min.css" />
  <style>
    .form-select {
      width: 103px;
      display: inline-block;
    }

    .col-form-label {
      text-align: right;
    }

    .figure-img {
      width: 100px;
      height: 100px;
      cursor: pointer;
    }

    #upload {
      display: none;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1 class="p-5">个人设置</h1>
    <form class="col-6">
      <div class="row mb-3">
        <label class="col-form-label col-3">昵称：</label>
        <div class="col-9">
          <input class="form-control col-9" type="text" name="nickname" />
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-form-label col-3">籍贯：</label>
        <div class="col-9">
          <select class="form-select col-4" name="province">
            <option value="">--省--</option>
          </select>
          <select class="form-select col-4" name="city">
            <option value="">--市--</option>
          </select>
          <select class="form-select col-4" name="area">
            <option value="">--区--</option>
          </select>
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-form-label col-3">头像：</label>
        <div class="col-9">
          <input class="form-control col-9" type="hidden" name="avatar" />
          <figure class="figure">
            <input type="file" id="upload" />
            <img src="https://yanxuan-item.nosdn.127.net/12a882699bd531a1bd428bffe1989525.jpg"
              class="figure-img img-fluid rounded" alt="..." />
            <figcaption class="figure-caption">修改头像</figcaption>
          </figure>
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-3"></label>
        <div class="col-9">
          <button class="btn btn-primary">保存</button>
        </div>
      </div>
    </form>
  </div>

  <script src="./lib/bootstrap.min.js"></script>
  <script src="./lib/axios.js"></script>
  <script src="./lib/form-serialize.js"></script>
  <script>
    // 在线接口文档：https://www.showdoc.com.cn/1834761734600444/8477923164668939

    // 配置请求根路径
    axios.defaults.baseURL = 'http://ajax-api.itheima.net'

    // 昵称
    let nameInput = document.querySelector('[name=nickname]')

    // 头像
    let upload = document.querySelector('#upload')
    let avatarImg = document.querySelector('.figure img')
    // 隐藏域
    let hiddenAvatar = document.querySelector('[name=avatar]')

    // 省市区
    let form = document.querySelector('form')
    let provinceSelect = document.querySelector('[name=province]')
    let citySelect = document.querySelector('[name=city]')
    let areaSelect = document.querySelector('[name=area]')


    // ========================================= 渲染展示功能 =========================================
    // 获取数据结果，展示到页面中
    //渲染个人信息函数
    const renderMsg = async function () {
      const { data: res } = await axios.get('/api/settings')
      console.log(res)
      if (res.data.city === '北京') {
        res.data.city = '北京市'
      }
      nameInput.value = res.data.nickname
      avatarImg.src = res.data.avatar
      const { data: resPv } = await axios.get('/api/province')
      const pvhtml = resPv.data.map((item) => `<option value="${item}">${item}</option>`).join('')
      provinceSelect.innerHTML = `<option value="">--省--</option>${pvhtml}`
      provinceSelect.value = res.data.province
      const { data: resCity } = await axios.get('/api/city', { params: { pname: res.data.province } })
      // console.log(resCity)
      const cityhtml = resCity.data.map((item) => `<option value="${item}">${item}</option>`).join('')
      citySelect.innerHTML = `<option value="">--市--</option>${cityhtml}`
      citySelect.value = res.data.city
      const { data: resArea } = await axios.get('/api/area', { params: { pname: res.data.province, cname: res.data.city } })
      // console.log(resArea)
      const areahtml = resArea.data.map((item) => `<option value="${item}">${item}</option>`).join('')
      areaSelect.innerHTML = `<option value="">--区--</option>${areahtml}`
      areaSelect.value = res.data.area
    }
    renderMsg()

    // ========================================= 省市切换功能 =========================================
    //渲染城市
    async function renderProvince() {
      const { data: res } = await axios.get('/api/province')
      console.log(res)
      // 省切换
      const pvhtml = res.data.map((item) => `<option value="${item}">${item}</option>`).join('')
      // <option value="">--省--</option>
      provinceSelect.innerHTML = `<option value="">--省--</option>${pvhtml}`
      // 市切换
      provinceSelect.addEventListener('change', async function () {
        citySelect.value = ''
        areaSelect.value = ''
        const { data: res } = await axios.get('/api/city', { params: { pname: this.value } })
        const cityhtml = res.data.map((item) => `<option value="${item}">${item}</option>`).join('')
        citySelect.innerHTML = `<option value="">--市--</option>${cityhtml}`
      })
      citySelect.addEventListener('change', async function () {
        const { data: res } = await axios.get('/api/area', { params: { pname: provinceSelect.value, cname: this.value } })
        const areahtml = res.data.map((item) => `<option value="${item}">${item}</option>`).join('')
        areaSelect.innerHTML = `<option value="">--区--</option>${areahtml}`
      })
    }
    renderProvince()

    // ========================================= 头像上传功能 =========================================
    // 点击图片，模拟点击文件域
    avatarImg.addEventListener('click', function () {
      hiddenAvatar.type = 'file'
      hiddenAvatar.style.display = 'none'
      hiddenAvatar.click()
    })

    // 头像change
    hiddenAvatar.addEventListener('change', async function () {
      // 用户选择的文件，该如何拿到？
      console.log(this.files[0])

      // 当this.files[0] 是undefined的时候，表示用户未选中文件，以下代码不用执行
      if (!this.files[0]) {
        return // 阻止后续代码的执行
      }

      // FormData 构造函数 new一起使用
      let fd = new FormData()
      fd.append('avatar', this.files[0])
      const { data: res } = await axios.post('/api/file', fd)
      console.log(res)
      avatarImg.src = res.data.url

      // axios 发请求代码
      // axios({
      //   method: 'post',
      //   // 请求的url地址一定要从接口文档中去复制
      //   url: 'http://www.liulongbin.top:3006/api/upload/avatar',
      //   // data的值是fd（把FormData存的数据给发送到服务器上）
      //   data: fd
      // }).then(({ data: res }) => {
      //   console.log(res)

      //   // 更换图片（以下写法有问题，res.url 缺少根路径）
      //   // img.src = res.url // error

      //   img.src = `http://www.liulongbin.top:3006${res.url}`
      // })
    })


    // ========================================= 保存功能 ========================================= 
    form.addEventListener('submit', function (e) {
      e.preventDefault()
    })

  </script>
</body>

</html>